package com.yisu.expressway.onedollar.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.model.WinningAlgorithmItem;
import com.yisu.expressway.onedollar.model.WinningAlgorithmObj;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.utils.SpannableUtil;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Kaven on 2016/12/9.
 */
public class LuckyNoIntroActivity extends BasicActivity
        implements PagingRecyclerView.SampleActionListener {
    private static final String EXTRA_KEY_GOODS_NO = "extra_key_goods_no";
    private static final String EXTRA_KEY_PERIODS_NO = "extra_key_periods_no";
    @Bind(R.id.rootView)
    protected View mRootView;
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.tv_lucknum_1)
    protected TextView mCountTv;
    @Bind(R.id.tv_lucknum_value)
    protected TextView mValueTv;
    @Bind(R.id.tv_luckNumber)
    protected TextView mLuckNumTv;
    @Bind(R.id.ll_joiners)
    protected View mJoinersView;
    @Bind(R.id.ll_result)
    protected View mResultView;
    @Bind(R.id.rv_content)
    protected PagingRecyclerView pagingRecyclerView;
    @Bind(R.id.tv_expand)
    protected TextView mExpandTv;
    private long mGoodsNo;
    private long mPeriodsNo;
    private WinningAlgorithmObj mWinningAlgorithmObj;

    public static void launch(Context context, long goodsNo, long periodsNum) {
        Intent intent = new Intent(context, LuckyNoIntroActivity.class);
        intent.putExtra(EXTRA_KEY_GOODS_NO, goodsNo);
        intent.putExtra(EXTRA_KEY_PERIODS_NO, periodsNum);
        context.startActivity(intent);
    }

    @OnClick(R.id.tv_expand)
    public void onClick() {
        if (getString(R.string.expand).equals(mExpandTv.getText())) {
            mJoinersView.setVisibility(View.VISIBLE);
            mResultView.setVisibility(View.GONE);
            mExpandTv.setText(getString(R.string.collapse));
        } else if (getString(R.string.collapse).equals(mExpandTv.getText())) {
            mJoinersView.setVisibility(View.GONE);
            mResultView.setVisibility(View.VISIBLE);
            mExpandTv.setText(getString(R.string.expand));
        }
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.activity_lucky_no_intro;
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    protected void releasePresenter() {

    }

    @Override
    protected void getIntentData(Intent intent) {
        mGoodsNo = intent.getLongExtra(EXTRA_KEY_GOODS_NO, -1);
        mPeriodsNo = intent.getLongExtra(EXTRA_KEY_PERIODS_NO, -1);
        if (mGoodsNo <= 0 || mPeriodsNo <= 0) {
            finish();
            return;
        }
    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {
        DividerListItemDecoration mListDivider = new DividerListItemDecoration(this,
                LinearLayoutManager.VERTICAL);
        pagingRecyclerView.init(mListDivider, new LinearLayoutManager(this), this, 20);
        getWinningAlgorithm();
        mExpandTv.setText(getString(R.string.expand));

    }

    private void getWinningAlgorithm() {
        if (mGoodsNo <= 0 || mPeriodsNo <= 0) {
            return;
        }
        Map<String, Object> params = new HashMap();

        params.put("goodsNo", mGoodsNo);
        params.put("periodsNum", mPeriodsNo);
        ApiClientHelper.postApi(ApiSetting.getWinningAlgorithm(),
                new TypeToken<WinningAlgorithmObj>() {
                }, new JSONObject(params), new Response.Listener<ApiResult<WinningAlgorithmObj>>() {
                    @Override
                    public void onResponse(ApiResult<WinningAlgorithmObj> result) {
                        if (!result.success) {
                            refreshView(false);
                            return;
                        }

                        mWinningAlgorithmObj = result.getResult();
                        refreshView(true);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        refreshView(false);
                    }
                }, this);
    }

    private void refreshView(boolean bSuc) {
        if (bSuc) {
            mRootView.setVisibility(mWinningAlgorithmObj != null ? View.VISIBLE : View.GONE);
            if (mWinningAlgorithmObj != null) {
                if (mWinningAlgorithmObj.winningAlgorithmVos != null) {
                    String format = String.format(
                            getString(R.string.one_dollar_lucky_num_a_detail_1),
                            mWinningAlgorithmObj.winningAlgorithmVos.size());
                    mCountTv.setText(format);
                }
                if (mWinningAlgorithmObj.defaultNum > 0) {
                    String format = String.format(getString(R.string.one_dollar_lucky_num_value),
                            mWinningAlgorithmObj.defaultNum);
                    mValueTv.setText(SpannableUtil.setHighLight(this, format,
                            format.substring(0, 1), R.color.oneDollarTextGrey));
                }
                if (mWinningAlgorithmObj.defaultNum > 0) {
                    String format = String.format(getString(R.string.one_dollar_luck_num),
                            mWinningAlgorithmObj.luckyNum);
                    mLuckNumTv.setText(SpannableUtil.setHighLight(this, format,
                            format.substring(0, 5), R.color.oneDollarTextGrey));
                }
            }
	        List<WinningAlgorithmItem> winningAlgorithmVos = mWinningAlgorithmObj.winningAlgorithmVos;
	        if (winningAlgorithmVos == null) {
		        return;
	        }
	        pagingRecyclerView.dataFetchDone(winningAlgorithmVos);
        } else {
            mRootView.setVisibility(View.GONE);
        }
    }

    @Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finish();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
    }

    @Override
    protected boolean isNeedLogin() {
        return false;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    @Override
    public void fetchData(int start, int pageSize) {
        if (mWinningAlgorithmObj == null) {
            return;
        }
        List<WinningAlgorithmItem> winningAlgorithmVos = mWinningAlgorithmObj.winningAlgorithmVos;
        if (winningAlgorithmVos == null) {
            return;
        }
        pagingRecyclerView.dataFetchDone(winningAlgorithmVos);
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = getLayoutInflater().inflate(R.layout.onedollar_joinner_item_list, null);
        return new JoinnerViewHolder(itemView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {
        final JoinnerViewHolder holder = (JoinnerViewHolder) _holder;
        final WinningAlgorithmItem item = (WinningAlgorithmItem) _item;
        holder.mTimeTv.setText(TextUtils.isEmpty(item.orderTime) ? "" : item.orderTime);

        long algorithmNum = item.algorithmNum;
        if (algorithmNum <= 0) {
            holder.mLuckyNumTv.setText("");
        } else {
            String format = String.format(getString(R.string.arrow), algorithmNum);
            holder.mLuckyNumTv.setText(format);
        }
        holder.mUserNameTv.setText(TextUtils.isEmpty(item.userName)
                ? (TextUtils.isEmpty(item.userAccount) ? "" : item.userAccount ): item.userName);
    }

    class JoinnerViewHolder extends BaseRvAdapter.SampleViewHolder {
        @Bind(R.id.tv_time)
        protected TextView mTimeTv;
        @Bind(R.id.tv_luckNumber)
        protected TextView mLuckyNumTv;
        @Bind(R.id.tv_user_name)
        protected TextView mUserNameTv;

        public JoinnerViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
